package com.ohuang.util_a.task.rxtask;

import java.util.Timer;
import java.util.TimerTask;

class RxMapTask<T, R> {
    RxMapTask(long timeOut, int maxCount, RxTaskRunnable<T, R> trRxTaskRunnable, RxTask rxTask) {
        this.timeOut = timeOut;
        this.maxCount = maxCount;
        this.trRxTaskRunnable = trRxTaskRunnable;
        this.rxTask=rxTask;

    }

    RxMapTask(RxTaskRunnable<T, R> trRxTaskRunnable, RxTask rxTask) {
        this.trRxTaskRunnable = trRxTaskRunnable;
        this.rxTask=rxTask;
    }

    RxTask rxTask;

    //单次任务超时时间
    private long timeOut = 0;

    //最大失败次数  小于0一直重新运行,直到成功
    int maxCount = 1;
    int index = 0;
    private Timer timer;
    RxTaskRunnable<T, R> trRxTaskRunnable;

    void run(T t, RXTaskCallBack<R> taskCallBack) {
        if (rxTask.isStop()){
            taskCallBack.onFair();
            return;
        }
        if (index < maxCount || maxCount < 0) {
            index++;
            RXTaskCallBack<R> rrxTaskCallBack = create(t, taskCallBack);
            if (timeOut > 0) {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        rrxTaskCallBack.onFair();
                    }
                }, timeOut);
            }
            runTask(t, rrxTaskCallBack);
        } else {
            taskCallBack.onFair();
        }
    }

    private void runTask(T t, RXTaskCallBack<R> taskCallBack) {
        trRxTaskRunnable.run(t, taskCallBack);
    }

    private RXTaskCallBack<R> create(T t, RXTaskCallBack<R> taskCallBack) {
        return new RXTaskCallBack<R>() {
            boolean isCall = false;


            @Override
            public void onSuccess(R r) {
                if (!isCall) {
                    isCall = true;
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    taskCallBack.onSuccess(r);

                }
            }

            @Override
            public void onFair() {
                if (!isCall) {
                    isCall = true;
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    run(t, taskCallBack);
                }
            }
        };
    }


}
